<?php

function processGetUserHistoryRequest(GetUserHistoryRequest $request) {
    $user_row = RequestUtils::testSession($request->sessionID);

    //id of user whose history is requested
    $user_id = $user_row['id'];

    $user_type = $user_row['user_type'];

    if ($request->userID >= 0 && $request->userID != $user_id) {
        if ($user_type === 'Participant')
            throwBusinessLogicError(0);
        $user_id = $request->userID; //don't test now that contest admin may request only his contest
    }

    if (!is_numeric($user_id))
        throwBusinessLogicError(2);

    $result = new GetUserHistoryResponse();

    $result->historyLines = array();

    $prfx = DB_PREFIX;

    $from_id = intval($request->fromId);
    $to_id = intval($request->toId);
    $condition = '';
    if ($from_id >= 0)
        $condition .= " AND (id >= $from_id OR test_id >= $from_id)";
    if ($to_id >= 0)
        $condition .= " AND (id <= $to_id OR test_id <= $to_id)";

    $query = "
        SELECT `submission`, `result`, `problem_id`, `submission_time`, `contest_id`, `id`, `test_id`
        FROM ${prfx}submission_history
        WHERE user_id=$user_id $condition
        ORDER BY id
    ";

    $rows = Data::getRows($query);
    $problem2attempt = array(); //problem_id -> already found attempts (0 initially)
    while ($row = Data::getNextRow($rows)) {
        $hl = new UserHistoryLine();

        $hl->problemId = intval($row['problem_id']);
        $hl->submissionTime = DateMySQLToPHP($row['submission_time']);

        $at = @$problem2attempt[$hl->problemId];
        if (!isset($at))
            $at = 1;
        else
            $at = $at + 1;
        $problem2attempt[$hl->problemId] = $at;
        $hl->attempt = $at;

        $res = $row['result'];
        $hl->results = $res ? Data::_unserialize($res) : null;

        if ($request->sendSubmissions)
            $hl->submission = Data::_unserialize($row['submission']);
        else
            $hl->submission = null;

        $hl->submissionId = intval($row['id']);
        $hl->testId = intval($row['test_id']);

        $cid = $row['contest_id'];

        $result->historyLines[] = $hl;
    }

    //test that contest admin may request only users of his contest
    if (isset($cid) && $user_type === 'ContestAdmin' && $user_row['contest_id'] != $cid)
        throwBusinessLogicError(0);

    return $result;
}

?>